//
//  MCPullMenuViewController.m
//  TLYLSF
//
//  Created by MC on 2017/6/7.
//  Copyright © 2017年 MC. All rights reserved.
//

#import "MCPullMenuViewController.h"
#import "MCCollectionViewFlowLayout.h"
#import "MCPullMenuCollectionViewCell.h"
#import "MCPullMenuTableViewCell.h"
#import <Masonry/Masonry.h>
#import "CellModel.h"
#import "MCPullMenuModel.h"
#import "MJExtension.h"
#define ScreenBounds [[UIScreen mainScreen] bounds]
#define ScreenWidth ScreenBounds.size.width
#define ScreenHeight ScreenBounds.size.height
@interface MCPullMenuViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
UITableViewDelegate,
UITableViewDataSource
>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UICollectionView * collectionView;
@property(nonatomic, strong)NSMutableArray*marr_Section;
@property(nonatomic,strong) NSMutableArray * marr_Cell;
@property(nonatomic,strong) NSMutableArray * marr_Left;
@property(nonatomic,strong) NSMutableArray * marr_Right;
@property(nonatomic,strong) NSMutableDictionary * mdic_Right;
@property(nonatomic,strong) NSDictionary   * dic_CZHelper;
@property(nonatomic,strong) NSDictionary   * dic_CZ;
@property(nonatomic,strong) NSDictionary   * dic_WF;
@end

@implementation MCPullMenuViewController
-(NSDictionary *)dic_CZ{
    if (!_dic_CZ) {

        NSData *JSONData_CZ = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LotteryJSON_CZ.json" ofType:nil ]];
        _dic_CZ = [NSJSONSerialization JSONObjectWithData:JSONData_CZ options:NSJSONReadingAllowFragments error:nil];
    }
    return _dic_CZ;
}

-(NSDictionary *)dic_CZHelper{
    if (!_dic_CZHelper) {
        NSData *JSONData_CZHelper = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LotteryJSON_CZHelper.json" ofType:nil ]];
        _dic_CZHelper = [NSJSONSerialization JSONObjectWithData:JSONData_CZHelper options:NSJSONReadingAllowFragments error:nil];
    }
    return _dic_CZHelper;
}
-(NSDictionary *)dic_WF{
    if (!_dic_WF) {
        NSData *JSONData_WF = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LotteryJSON_WF.json" ofType:nil ]];
        _dic_WF = [NSJSONSerialization JSONObjectWithData:JSONData_WF options:NSJSONReadingAllowFragments error:nil];
    }
    return _dic_WF;
}

- (void)viewDidLoad {
    [super viewDidLoad];


    
    [self updatePreferredContentSizeWithTraitCollection:self.traitCollection];
    [self  setProperty];
    [self  createUI];
    [self  loadData];
    

}



-(void)loadData{

    /*
     *  根据传入的ID  获取彩种信息
     */
    NSDictionary * czInfo=[self.dic_CZHelper objectForKey:_lotteryId];
    MCCZHelperModel * modelCZ=[MCCZHelperModel mj_objectWithKeyValues:czInfo];
    NSLog(@"%@-%@-%@-%@",modelCZ.tag,modelCZ.type,modelCZ.name,modelCZ.logo);
    
    /*
     * 根据type找出玩法
     */
//    玩法一级数组
    _marr_Left=[[self.dic_WF objectForKey:modelCZ.type] objectForKey:@"playType"];
//    玩法二级字典组
    _mdic_Right=[[self.dic_WF objectForKey:modelCZ.type] objectForKey:@"playMethod"];
    
    /*
     * 默认选中第一级玩法的第一个
     */
    MC_PlayType_Model * modelF = [MC_PlayType_Model mj_objectWithKeyValues:_marr_Left[0]];
    _marr_Right=[_mdic_Right objectForKey:modelF.typeId];
    
    [_marr_Section removeAllObjects];
    for(int i=0 ;i<_marr_Left.count; i++){
        CellModel* model =[[CellModel alloc]init];
        model.reuseIdentifier = NSStringFromClass([MCPullMenuTableViewCell class]);
        model.className=NSStringFromClass([MCPullMenuTableViewCell class]);
        model.height = [MCPullMenuTableViewCell computeHeight:nil];
        model.selectionStyle=UITableViewCellSelectionStyleNone;
        model.accessoryType=UITableViewCellAccessoryNone;
        /*
         * 传递参数
         */
        model.userInfo = [_marr_Left objectAtIndex:i];
        
        SectionModel *model0=[SectionModel sectionModelWithTitle:@"" cells:@[model]];
        model0.headerhHeight=0.0001;
        model0.footerHeight=10;
        [_marr_Section addObject:model0];
    }
    
    [_tableView reloadData];
    [self reloyOutCollectionView];
    /*
     * 设置默认选中
     */
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; //  设置默认选中的行
    MCPullMenuTableViewCell *ex_cell = [_tableView cellForRowAtIndexPath:indexPath];
    [ex_cell setSelected:YES animated:YES];  // 使cell 的 状态设置为选中状态

    
}

-(void)reloyOutCollectionView{
    [_marr_Cell    removeAllObjects];
    for (int i=0; i<_marr_Right.count; i++) {
        CollectionModel * model0=[[CollectionModel alloc]init];
        model0.header_size=CGSizeMake(ScreenWidth, 40);
        model0.item_size=CGSizeMake((ScreenWidth-150-40)/2.0, 40);
        model0.section_color=[UIColor whiteColor];
        model0.section_Edge=UIEdgeInsetsMake(0, 0, 0, 0);
        model0.interitemSpacing=0.1;
        model0.lineSpacing=10;
        model0.isHaveHeader=YES;
        model0.id_dentifier=NSStringFromClass([MCPullMenuCollectionViewCell class]);
        [_marr_Cell addObject:model0];
    }
    
    [self.collectionView reloadData];
}






#pragma mark==================setProperty======================
-(void)setProperty{
    _marr_Left=[[NSMutableArray alloc]init];
    _marr_Right=[[NSMutableArray alloc]init];
    _mdic_Right=[[NSMutableDictionary alloc]init];
    _marr_Section=[[NSMutableArray alloc]init];
    _marr_Cell=[[NSMutableArray alloc]init];

    self.view .backgroundColor = [UIColor grayColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title=NSStringFromClass([self class]);
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    
}


#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    _tableView.frame=CGRectMake(0, 0, 149, 300);

    [self.view addSubview:self.collectionView];
    self.collectionView.frame=CGRectMake(150, 0, ScreenWidth-150, 300);

    
}
#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([MCPullMenuTableViewCell class])]) {
        MCPullMenuTableViewCell *ex_cell=(MCPullMenuTableViewCell *)cell;
        [ex_cell relayOutUIWithModel:cm.userInfo];
//        if (indexPath.section==0&&indexPath.row==0) {
//
//            
//            
//            [ex_cell setSelected:YES ];
//            [ex_cell setSelected:YES animated:YES];
//            ex_cell.lab_type.backgroundColor = [UIColor cyanColor];
//        }
        
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    MCPullMenuTableViewCell *ex_cell=[tableView cellForRowAtIndexPath:indexPath];
//    ex_cell.lab_type.backgroundColor = [UIColor cyanColor];
    
    
    /*
     * 默认选中第一级玩法的第一个
     */
    MC_PlayType_Model * modelF = [MC_PlayType_Model mj_objectWithKeyValues:_marr_Left[indexPath.section]];
    _marr_Right=[_mdic_Right objectForKey:modelF.typeId];
    [self reloyOutCollectionView];
    
    
}

#pragma ===========================================
/*
 * collectionView
 */
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        
        //创建一个layout布局类
        MCCollectionViewFlowLayout * layout = [[MCCollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.dataSource=self;
        _collectionView.delegate=self;
        [_collectionView registerClass:[MCPullMenuCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MCPullMenuCollectionViewCell class])];
        
    }
    return _collectionView;
}
#pragma mark - <UICollectionViewDataSource>
// 设置headerView和footerView的
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        return nil ;
    }
    return nil ;
}
//// 设置section头视图的参考大小，与tableheaderview类似
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    BKIntegralCollectionModel * model=self.marr_Cell[section];
//    return model.header_size;
//}
//设置section的颜色
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Cell[section];
    return model.section_color;
}
//设置item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionModel * model=self.marr_Cell[indexPath.section];
    return model.item_size;
}
//设置section的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Cell[section];
    return model.section_Edge;
}
// 两个cell之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Cell[section];
    return model.interitemSpacing;
}
// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    CollectionModel * model=self.marr_Cell[section];
    return model.lineSpacing;
}

//numberOfItemsInSection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    CollectionModel * model=self.marr_Cell[section];
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        return self.marr_Cell.count;
    }
    return 0;
}

//numberOfSections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//UICollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell*  cell=nil;
    CollectionModel * model=self.marr_Cell[indexPath.section];
    if (model.id_dentifier) {
        cell =[collectionView dequeueReusableCellWithReuseIdentifier:model.id_dentifier forIndexPath:indexPath];
    }
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        
        MCPullMenuCollectionViewCell *ex_cell=(MCPullMenuCollectionViewCell *)cell;
        [ex_cell relayOutUIWithModel:[_marr_Right objectAtIndex:indexPath.row]];
        
       
    }
    return cell;
}
//didSelect
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CollectionModel * model=self.marr_Cell[indexPath.section];
    if ([model.id_dentifier isEqualToString:NSStringFromClass([MCPullMenuCollectionViewCell class])]) {
        if ([self.delegate respondsToSelector:@selector(selectLotteryKindWithTag:)]) {
            
            NSDictionary * czInfo=[self.dic_CZHelper objectForKey:_lotteryId];
            MCCZHelperModel * modelCZ=[MCCZHelperModel mj_objectWithKeyValues:czInfo];
//            NSLog(@"%@-%@-%@-%@",modelCZ.tag,modelCZ.type,modelCZ.name,modelCZ.logo);
            NSString * str_CZ=[[_marr_Right objectAtIndex:indexPath.row] objectForKey:@"name"];
            NSString * str=[NSString stringWithFormat:@"你选择了【%@】里面的【%@】\n",modelCZ.name,str_CZ];
            
            [self.delegate selectLotteryKindWithTag:str];
            [self dismissViewControllerAnimated:YES completion:NULL];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
    [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator];
    
    [self updatePreferredContentSizeWithTraitCollection:newCollection];
}

- (void)updatePreferredContentSizeWithTraitCollection:(UITraitCollection *)traitCollection{
    self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, 300);
    
}


@end




























